package javaweb_work01.login.Servlet;

import javaweb_work01.login.Entity.User;
import javaweb_work01.login.service.UserService;
import javaweb_work01.main.Utils.PageContrl;
import javaweb_work01.main.Entity.Students;
import javaweb_work01.main.Service.CountService;
import javaweb_work01.main.Service.ShowService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 负责登录操作的Servlet类
 */
@WebServlet(name = "indexServlet", urlPatterns = "/index")
public class indexServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到index.jsp传来的表单信息，即用户名和密码
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        //校验步骤
        //声明UserService的对象
        UserService userService = new UserService();
        //利用得到的用户名和密码构造新的User对象,作为参数传入Service中，最后调用Dao层的方法，返回一个User类型的对象
        User user = userService.userLoginService(new User(userName, password));
        //判断，如果返回值为空，即数据库中没有对应的数据，登录失败
        if(null == user){
            //储存名称为error的属性，即提示信息
            request.setAttribute("error","登录失败，用户名/密码错误");
            //服务器内跳转到index.jsp
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            //将request和response对象转发
            requestDispatcher.forward(request,response);
        //登录成功
        }else {
            //将登录的用户信息放入session中实现多个请求的共享
            request.getSession().setAttribute("user",user);

            //获取主页需要显示的信息，构建主页
            //声明CountService类的对象，以便调用方法
            CountService countService = new CountService();
            //调用Service中的方法，最后调用Dao层方法，返回数据库中的数据总数，即学员总数
            int count = countService.countStudentsService();
            //利用得到的学员总数构造新的PageContrl对象，用于分页显示，此处为从第0条开始，显示10条
            PageContrl pageContrl = new PageContrl(0,10,count);
            //声明ShowService类的对象
            ShowService showService = new ShowService();
            //利用ShowService类的对象调用方法，最后调用Dao层方法，返回数据库中该页需要显示的学员信息
            List<Students> students = showService.showStudentsService(pageContrl);

            //将得到的PageContrl对象和Students对象放入session中实现共享
            request.getSession().setAttribute("pageContrl",pageContrl);
            request.getSession().setAttribute("showStudents",students);
            //跳转到主页
            response.sendRedirect("main.jsp");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
